package cn.bonoon.kernel.descriptors.impl;

import java.util.HashMap;
import java.util.Map;

import cn.bonoon.kernel.annotations.ResetProperties;
import cn.bonoon.kernel.annotations.ResetProperty;
import cn.bonoon.kernel.descriptors.ClassPropertyAccessor;

abstract class MappableClassDescriptor<T extends ClassPropertyAccessor> extends AbstractClassDescriptor<T>{

	private final Map<String, ResetProperty> renames = new HashMap<String, ResetProperty>();
	
	protected MappableClassDescriptor(Class<?> clazz) {
		super(clazz);
		readReset(clazz);
	}
	
	/**
	 * 对定义类的预处理，这些处理需要在调用初始化函数{@link #initDescriptor()}之前进行
	 * @param clazz
	 */
	private void readReset(Class<?> clazz){
		ResetProperty pr = clazz.getAnnotation(ResetProperty.class);
		if(null != pr){
			putReset(pr);
		}
		ResetProperties prs = clazz.getAnnotation(ResetProperties.class);
		if(null != prs){
			for(ResetProperty tpr : prs.value()){
				putReset(tpr);
			}
		}
		
		//当前类下接口定义的优先于父类(以及父类的接口)的定义
		Class<?>[] itfs = clazz.getInterfaces();
		for(Class<?> itf : itfs){
			readReset(itf);
		}
		
		Class<?> pre = clazz.getSuperclass();
		if(null != pre && !Object.class.equals(pre)){
			readReset(pre);
		}
	}
	
	private void putReset(ResetProperty pr){
		String name = pr.value();
		if(!renames.containsKey(name)){
			renames.put(name, pr);
		}
	}
	
	public ResetProperty getPropertyReseter(String key){
		return renames.get(key);
	}
}
